import React, { Component } from 'react'

export default class Shopcart extends Component {
  state={
    shopcartList:[
        {
            id:'1001',
            name:'旺仔牛奶',
            price:5.6,
            num:1
        },
        {
            id:'1002',
            name:'哇哈哈纯净水',
            price:1.2,
            num:1
        },
        {
            id:'1003',
            name:'AD钙奶',
            price:4.5,
            num:1
        }
    ]
  }
  changeNum=(op,id)=>{
    switch(op){
        case '+':
            let result=this.state.shopcartList.find(item=>{
                if(item.id==id){
                    return true
                }
            })
            result.num++
            this.setState({
                shopcartList:this.state.shopcartList
            })
        break
        case '-':
            let newShopcartList=this.state.shopcartList.map(item=>{
                if(item.id===id){
                    if(item.num>0){
                        item.num--
                    }else{
                        window.alert('商品的数量不能小于1')
                    }
                  
                }
                return item
            })
            this.setState({shopcartList:newShopcartList})
            break
    }
  }
  //使用get访问器模拟计算属性,这种方式是不能完全模拟的
  get totalPrice(){
     return `￥${this.state.shopcartList.reduce((prev,cur)=>prev+cur.price*cur.num,0).toFixed(2)}`
  }
  render() {
    const {shopcartList}=this.state
    let shopcartHeader=['序号','名称','价格','数量','小计']
    return (
      <div>
        <h1>购物车案例</h1>
        <table>
            <thead>
                <tr>
                    {
                        shopcartHeader.map(item=><td key={item}>{item}</td>)
                    }
                </tr>
            </thead>
            <tbody>
                {
                    shopcartList.map(item=><tr key={item.id}>
                        <td>{item.id}</td>
                        <td>{item.name}</td>
                        <td>￥{item.price}</td>
                        <td>
                            <button onClick={()=>this.changeNum('-',item.id)}>-</button>
                            <span>{item.num}</span>
                            <button onClick={()=>this.changeNum('+',item.id)}>+</button>
                        </td>
                        <td>￥{(item.num*item.price).toFixed(2)}</td>
                    </tr>)
                }
            </tbody>
            <tfoot>
                <tr>
                    <td colSpan={5}>
                        总计：{this.totalPrice}
                    </td>
                </tr>
            </tfoot>
        </table>
      </div>
    )
  }
}
